package com.oracle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oracle.mapper.TeacherMapper;
import com.oracle.pojo.LoginForm;
import com.oracle.pojo.Student;
import com.oracle.pojo.Teacher;
import com.oracle.service.ITeacherService;
import com.oracle.util.MD5;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service("teacherServiceImpl")   // 指定当前实现类的id
@Transactional
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements ITeacherService {
    @Override
    public Teacher login(LoginForm loginForm) {
        QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
        // 使用teacherQueryWrapper设定查询语句的筛选条件，相当于where后面的语句
        // tb_teacher数据表中的name字段和登录页面对象中的username属性匹配
        teacherQueryWrapper.eq("name",loginForm.getUsername());
        // tb_teacher数据表中的通过MD5加密后的password字段和登录页面对象中的password属性匹配
        // 这里的第二个参数需要使用MD5加密，因为数据库中的password字段存储的是通过MD5加密后的值
        teacherQueryWrapper.eq("password", MD5.encrypt(loginForm.getPassword()));
        // 使用MybatisPlus的内置baseMapper调用查询单个方法，查询数据库的Teacher对象
        Teacher teacher = baseMapper.selectOne(teacherQueryWrapper);
        // 方法返回Teacher对象
        return teacher;
    }

    @Override
    public Teacher getTeacherById(Long userId) {
        QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
        teacherQueryWrapper.eq("id",userId);
        return baseMapper.selectOne(teacherQueryWrapper);
    }

    @Override
    public IPage<Teacher> getTeachersByConditions(Page<Teacher> teacherPage, Teacher teacher) {
        QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(teacher.getName())){
            teacherQueryWrapper.like("name",teacher.getName());
        }
        if(!StringUtils.isEmpty(teacher.getClazzName())){
            teacherQueryWrapper.eq("clazz_name",teacher.getClazzName());
        }
        teacherQueryWrapper.orderByDesc("id");

        Page<Teacher> page = baseMapper.selectPage(teacherPage, teacherQueryWrapper);

        return page;
    }
}
